package com.gitee.jmliu1983.finacehelper.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;

//@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
public class WebSecurityConfigurer
{
    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    
    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;
    
    @Bean
    public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {

        http
        // 不使用CSRF保护，因为这不是一个浏览器应用（或者你可以根据需要启用它）
        .csrf(csrf ->csrf.disable())
        // 允许所有请求通过，不进行认证或授权
        .authorizeRequests((authz) -> authz
            .anyRequest().permitAll()
        )
        // 认证失败处理类
        .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
        // 添加JWT filter
        .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)     
        ;
        

    // 如果你有自定义的认证机制或需要其他配置，可以在这里添加
    // 例如：http.formLogin().disable() 或 http.httpBasic().disable() 等

    return http.build();
    }
}
